package com.example.testnt;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

public abstract class AbstractEchoActivity extends AppCompatActivity implements View.OnClickListener {

    static {
        System.loadLibrary("native-lib");
    }


    /**
     * 端口号
     */
    protected EditText portEdit;

    /**
     * 服务按钮
     */
    protected Button startButton;

    /**
     * 日志滚动
     */
    protected ScrollView logScroll;

    /**
     * 日志试图
     */
    protected TextView logView;

    /**
     * 布局id
     */
    private final int layoutID;

    public AbstractEchoActivity(int layoutID) {
        this.layoutID = layoutID;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(layoutID);

        portEdit = findViewById(R.id.port_edit);
        startButton = findViewById(R.id.start_button);
        logScroll = findViewById(R.id.log_scroll);
        logView = findViewById(R.id.log_view);

        startButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v == startButton) {

            onStartButtonClicked();
        }
    }

    protected abstract void onStartButtonClicked();

    protected Integer getPort() {

        Integer port;


        try {
            port = Integer.valueOf(portEdit.getText().toString());
        } catch (NumberFormatException e) {
            port = null;
        }
        return port;
    }

    public void logMessage(final String message) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                logMessageDirect(message);
            }
        });
    }

    protected void logMessageDirect(final String message) {

        logView.append(message);
        logView.append("\n");
        logScroll.fullScroll(View.FOCUS_DOWN);
    }
}
